/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.msg;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Contacts.Groups;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.TextView;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.activities.postcard.PostcardEditBackActivity;
import com.phonebooksharing.android.activities.postcard.PostcardViewActivity;
import com.phonebooksharing.android.async.SendPostcardMessageTask;
import com.phonebooksharing.android.async.SendTextMessageTask;
import com.phonebooksharing.android.async.SendVoiceMessageTask;
import com.phonebooksharing.android.util.CloseableUtil;
import com.phonebooksharing.android.util.GeneralUtils;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.IOUtilities;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.android.widgets.drawable.FastBitmapDrawable;
import com.phonebooksharing.dto.GenericTransferDTO;
import com.phonebooksharing.dto.friend.GroupItem;
import com.phonebooksharing.dto.msg.TextMessageItem;

public class MessageGroupSelection extends ListActivity {

    private GroupAdapter adapter;
    public static final String ID = "i", IS_VOICE_MSG = "m", IS_POST_CARD = "p";
    private ArrayList<Integer> groupSelection;
    private Dialog             msgDialog;

    private boolean            isVoice, isPostcard;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(R.layout.group_selection);
        getListView().setCacheColorHint(0);

        findViewById(R.id.actionStub).setVisibility(View.VISIBLE);
        isVoice = getIntent().getBooleanExtra(IS_VOICE_MSG, true);
        isPostcard = getIntent().getBooleanExtra(IS_POST_CARD, false);

        ((TextView) findViewById(android.R.id.text1)).setText("Select a group to send a message to");

        ((Button) findViewById(android.R.id.button1)).setVisibility(View.INVISIBLE);

        Button next = (Button) findViewById(android.R.id.button2);
        next.setText("Next");
        // next.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.next,
        // 0);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final ListView lv = getListView();
                final SparseBooleanArray sp = lv.getCheckedItemPositions();
                final ArrayList<GroupItem> list = adapter.groups;
                groupSelection = new ArrayList<Integer>();

                int size = list.size();
                for (int i = 0; i < size; i++) {
                    if (sp.get(i)) {
                        groupSelection.add(list.get(i).id);
                    }
                }

                if (groupSelection.size() > 0) {
                    if (isPostcard) {
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(Intent.createChooser(intent, "Get Picture"), ACTIVITY_PICK_IMAGE);

                    } else if (isVoice) {
                        Intent i = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
                        startActivityForResult(i, ACTIVITY_RECORD_SOUND);
                    } else {
                        showDialog(0);
                    }
                } else {
                    new AlertDialog.Builder(MessageGroupSelection.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("No Group Selection").setMessage(
                            "Please select at least one group to proceed.").setPositiveButton("OK", null).create().show();
                }
            }
        });

        View empty = LayoutInflater.from(this).inflate(R.layout.empty_progress, null);
        ((TextView) empty.findViewById(android.R.id.text1)).setText("Please wait while we load your groups.");

        final ListView lv = getListView();
        lv.setEmptyView(empty);
        lv.setItemsCanFocus(false);
        lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        new LoadGroupsTask(this).execute();
    }

    public static final int ACTIVITY_RECORD_SOUND = 0, ACTIVITY_PICK_IMAGE = 1, ACTIVITY_CROP_IMAGE = 2, ACTIVITY_EDIT_POSTCARD = 3, ACTIVITY_PREVIEW_POSTCARD = 4;

    private File            tempPostcardCrop;

    // private Bitmap front, back;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (RESULT_OK == resultCode) {
            switch (requestCode) {
            case ACTIVITY_RECORD_SOUND: {
                new SendVoiceMessageTask(this, groupSelection, data.getDataString()).execute("New Audio");
                break;
            }
            case ACTIVITY_PICK_IMAGE: {
                try {
                    if (tempPostcardCrop != null)
                        IOUtilities.add2collection(tempPostcardCrop.getAbsolutePath());
                    tempPostcardCrop = IOUtilities.getExternalFile(System.currentTimeMillis() + ".dat");
                } catch (IOException e) {
                    e.printStackTrace();
                }

                final Intent i = new Intent("com.android.camera.action.CROP");
                i.setClassName("com.android.camera", "com.android.camera.CropImage");
                i.setData(data.getData());
                i.putExtra("scale", true);
                i.putExtra("output", Uri.parse("file:/" + tempPostcardCrop.getAbsolutePath()));

                startActivityForResult(i, ACTIVITY_CROP_IMAGE);
                break;
            }
            case ACTIVITY_CROP_IMAGE: {
                final Intent i = new Intent(this, PostcardEditBackActivity.class);
                startActivityForResult(i, ACTIVITY_EDIT_POSTCARD);
                break;
            }
            case ACTIVITY_EDIT_POSTCARD: {
                // front =
                // BitmapFactory.decodeFile(tempPostcardCrop.getAbsolutePath());
                // back = Global.postCardBack;
                // Global.postCardBack = null;

                Global.setPostcard(new FastBitmapDrawable(BitmapFactory.decodeFile(tempPostcardCrop.getAbsolutePath())), null);
                
                // new Handler().postDelayed(new Runnable() {
                // @Override
                // public void run() {
                showDialog(1);
                // }
                // }, 3 * 1000);
            }
            case ACTIVITY_PREVIEW_POSTCARD: {
                showDialog(1);
            }
            default:
                break;
            }
        }
    }
    
    public static final String TEMP_POSTCARD_CROP = "t";

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        
        Log.i(Global.LOG_TAG, "Storing temp postcard = " + tempPostcardCrop);
        outState.putSerializable(TEMP_POSTCARD_CROP, tempPostcardCrop);
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle state) {
        super.onRestoreInstanceState(state);
        
        Serializable s = state.getSerializable(TEMP_POSTCARD_CROP);
        Log.i(Global.LOG_TAG, "Getting from storing temp postcard = " + s);
        if(s != null) {
            tempPostcardCrop = (File)s;
        }
    }

    protected View getTextMsgView() {
        LayoutInflater factory = LayoutInflater.from(this);
        final View messageView = factory.inflate(R.layout.post_text, null);
        messageView.findViewById(android.R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextMessageItem txtMsg = new TextMessageItem();
                txtMsg.title = ((TextView) messageView.findViewById(android.R.id.text1)).getText().toString();
                txtMsg.text = ((TextView) messageView.findViewById(android.R.id.text2)).getText().toString();
                txtMsg.when = GeneralUtils.getGmtTimeInMilis();

                GenericTransferDTO g = new GenericTransferDTO();
                g.authItem = Global.authItem;
                g.items2 = groupSelection;
                g.simpleItem = txtMsg;

                new SendTextMessageTask(MessageGroupSelection.this, String.format(Global.MESSAGE_SERVLET_URL, "cm" /*ac*/, "b" /*t*/, "" /*q*/, "" /*mt*/), g).execute();
            }
        });

        messageView.findViewById(android.R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgDialog.dismiss();
            }
        });

        return messageView;
    }

//    @Override
//    public void finish() {
//        Log.i("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa", "Finishing up activity");
//        Global.setPostcard(null, null);
//
//        super.finish();
//    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case 0: {
            msgDialog = new AlertDialog.Builder(MessageGroupSelection.this).setTitle("Enter your message").setView(getTextMsgView()).create();
            return msgDialog;
        }
        case 1: {
            return new AlertDialog.Builder(this).setTitle("Postcard Actions").setItems(R.array.postcard_preview_opt, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 0) {// preview
                        Intent i = new Intent(MessageGroupSelection.this, PostcardViewActivity.class);
                        // i.putExtra(PostcardViewActivity.FRONT_IMAGE, front);
                        // i.putExtra(PostcardViewActivity.BACK_IMAGE, back);

                        startActivityForResult(i, ACTIVITY_PREVIEW_POSTCARD);
                    } else if (which == 1) {// edit
                        final Intent i = new Intent(MessageGroupSelection.this, PostcardEditBackActivity.class);
                        startActivityForResult(i, ACTIVITY_EDIT_POSTCARD);
                    } else { // send
                        new SendPostcardTask(MessageGroupSelection.this, groupSelection).execute();
                    }
                }
            }).create();
        }
        default:
            break;
        }
        return null;
    }

    class SendPostcardTask extends SendPostcardMessageTask {
        public SendPostcardTask(Context cx, ArrayList<Integer> groupList) {
            super(cx, groupList);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            finish();
        }
    }

    static class GroupAdapter extends BaseAdapter {
        private ArrayList<GroupItem> groups;
        private LayoutInflater       inflater;

        public GroupAdapter(Context c, ArrayList<GroupItem> groups) {
            this.groups = groups;
            this.inflater = LayoutInflater.from(c);
        }

        public int getCount() {
            return groups.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View cv, ViewGroup parent) {
            ViewHolder holder;
            if (cv == null) {
                cv = inflater.inflate(R.layout.check_list_item_2line, parent, false);
                holder = new ViewHolder();
                // holder.icon1 =
                // (ImageView)cv.findViewById(android.R.id.icon1);
                holder.checkbox = (CheckedTextView) cv.findViewById(android.R.id.text1);// text1
                                                                                        // is
                                                                                        // just
                                                                                        // because
                                                                                        // there
                                                                                        // is
                                                                                        // no
                                                                                        // checkbox1
                holder.text1 = (TextView) cv.findViewById(android.R.id.title);
                // holder.text2 =
                // (TextView)cv.findViewById(android.R.id.summary);

                cv.setTag(holder);
            } else {
                holder = (ViewHolder) cv.getTag();
            }

            final GroupItem gi = groups.get(position);
            holder.text1.setText("Group: " + gi.name);
            // holder.text3.setText("Click on this group to change its privacy");
            // holder.text4.setText(getPrivacyMode(gi.getPrivacy()));

            holder.checkbox.setVisibility(View.VISIBLE);

            return cv;
        }

        // private String getPrivacyMode(int privacy) {
        // return "Privacy: " +
        // PrivacyGroupSetupActivity.PRIVACY_OPTIONS[privacy][0];
        // }

        static class ViewHolder {
            // ImageView icon1;
            CheckedTextView checkbox;
            TextView        text1, text2;
        }
    }

    class LoadGroupsTask extends NetworkHandlerTask<Void, ArrayList<GroupItem>, Void> {
        private Context c;

        LoadGroupsTask(Context c) {
            this.c = c;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @SuppressWarnings("unchecked")
        @Override
        protected Void doInBackground(Void... params) {

            final ContentResolver cr = c.getContentResolver();
            final ArrayList<GroupItem> list = new ArrayList<GroupItem>();
            Cursor c = null;
            try {

                Intent i = getIntent();
                c = cr.query(Groups.CONTENT_URI, null, Groups._ID + " <> ? AND " + Groups.NAME + " not in (?)", new String[] { "" + i.getIntExtra(ID, 0), "System Group: My Contacts" }, Groups.NAME);
                int id, name;
                if (c != null && c.moveToFirst()) {
                    id = c.getColumnIndex(Groups._ID);
                    name = c.getColumnIndex(Groups.NAME);
                    do {
                        list.add(new GroupItem(c.getInt(id), c.getString(name)));
                    } while (c.moveToNext());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                CloseableUtil.safeClose(c);
                c = null;
            }

            publishProgress(list);
            return null;
        }

        @Override
        protected void onProgressUpdate(ArrayList<GroupItem>... values) {
            super.onProgressUpdate(values);
            final ArrayList<GroupItem> list = values[0];
            adapter = new GroupAdapter(c, list);
            final ListView elv = getListView();
            elv.setAdapter(adapter);
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }
    }

    @Override
    protected void onDestroy() {
        if (tempPostcardCrop != null) {
            IOUtilities.add2collection(tempPostcardCrop.getAbsolutePath());
        }

        Global.postCardBack = null;
        Global.postCardFront = null;

        super.onDestroy();
    }
}
